package com.screen.screendisplay.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.coal.CoalProdoperOsv;
import com.screen.screendisplay.mapper.coal.CoalProdoperOsvMapper;
import com.screen.screendisplay.service.coal.CoalProdoperOsvService;
import com.screen.screendisplay.vo.coal.CoalStrippingVO;
import com.screen.screendisplay.vo.coal.CoalStrippingUnitsVO;
import com.screen.screendisplay.vo.coal.CoalStrippingTrendVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 生产经营土岩剥离量表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalProdoperOsvServiceImpl extends ServiceImpl<CoalProdoperOsvMapper, CoalProdoperOsv> implements CoalProdoperOsvService {

    @Override
    public CoalStrippingVO getStripping(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 获取当前月份
        int currentMonth = LocalDate.now().getMonthValue();
        
        CoalStrippingVO vo = new CoalStrippingVO();
        
        // 查询自有年度数据（unit_type=0, year_month_type=0）
        LambdaQueryWrapper<CoalProdoperOsv> ownAnnualQuery = new LambdaQueryWrapper<>();
        ownAnnualQuery.eq(CoalProdoperOsv::getYear, year)
                     .eq(CoalProdoperOsv::getYearMonthType, false)
                     .eq(CoalProdoperOsv::getUnitType, 0);
        CoalProdoperOsv ownAnnualData = this.getOne(ownAnnualQuery);
        
        if (ownAnnualData != null) {
            vo.setOwnAnnualPlan(ownAnnualData.getAnnualPlan());
            vo.setOwnAnnualActual(ownAnnualData.getAnnualActual());
            vo.setOwnAnnualCompletionRate(ownAnnualData.getAnnualCompletionRate());
            vo.setOwnAnnualYoyRate(ownAnnualData.getAnnualYoyRate());
        }
        
        // 查询外委年度数据（unit_type=1, year_month_type=0）
        LambdaQueryWrapper<CoalProdoperOsv> outsourceAnnualQuery = new LambdaQueryWrapper<>();
        outsourceAnnualQuery.eq(CoalProdoperOsv::getYear, year)
                           .eq(CoalProdoperOsv::getYearMonthType, false)
                           .eq(CoalProdoperOsv::getUnitType, 1);
        CoalProdoperOsv outsourceAnnualData = this.getOne(outsourceAnnualQuery);
        
        if (outsourceAnnualData != null) {
            vo.setOutsourceAnnualPlan(outsourceAnnualData.getAnnualPlan());
            vo.setOutsourceAnnualActual(outsourceAnnualData.getAnnualActual());
            vo.setOutsourceAnnualCompletionRate(outsourceAnnualData.getAnnualCompletionRate());
            vo.setOutsourceAnnualYoyRate(outsourceAnnualData.getAnnualYoyRate());
        }
        
        // 查询自有月度数据（unit_type=0, year_month_type=1, month=当前月）
        LambdaQueryWrapper<CoalProdoperOsv> ownMonthlyQuery = new LambdaQueryWrapper<>();
        ownMonthlyQuery.eq(CoalProdoperOsv::getYear, year)
                      .eq(CoalProdoperOsv::getMonth, currentMonth)
                      .eq(CoalProdoperOsv::getYearMonthType, true)
                      .eq(CoalProdoperOsv::getUnitType, 0);
        CoalProdoperOsv ownMonthlyData = this.getOne(ownMonthlyQuery);
        
        if (ownMonthlyData != null) {
            vo.setOwnMonthlyPlan(ownMonthlyData.getMonthlyPlan());
            vo.setOwnMonthlyActual(ownMonthlyData.getMonthlyActual());
            
            // 计算月完成率
            if (vo.getOwnMonthlyActual() != null && vo.getOwnMonthlyPlan() != null && vo.getOwnMonthlyPlan().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal monthlyCompletionRate = vo.getOwnMonthlyActual()
                        .divide(vo.getOwnMonthlyPlan(), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
                vo.setOwnMonthlyCompletionRate(monthlyCompletionRate.setScale(2, RoundingMode.HALF_UP));
            }
            
            vo.setOwnMonthlyYoyRate(ownMonthlyData.getMonthlyYoyRate());
        }
        
        // 查询外委月度数据（unit_type=1, year_month_type=1, month=当前月）
        LambdaQueryWrapper<CoalProdoperOsv> outsourceMonthlyQuery = new LambdaQueryWrapper<>();
        outsourceMonthlyQuery.eq(CoalProdoperOsv::getYear, year)
                            .eq(CoalProdoperOsv::getMonth, currentMonth)
                            .eq(CoalProdoperOsv::getYearMonthType, true)
                            .eq(CoalProdoperOsv::getUnitType, 1);
        CoalProdoperOsv outsourceMonthlyData = this.getOne(outsourceMonthlyQuery);
        
        if (outsourceMonthlyData != null) {
            vo.setOutsourceMonthlyPlan(outsourceMonthlyData.getMonthlyPlan());
            vo.setOutsourceMonthlyActual(outsourceMonthlyData.getMonthlyActual());
            
            // 计算月完成率
            if (vo.getOutsourceMonthlyActual() != null && vo.getOutsourceMonthlyPlan() != null && vo.getOutsourceMonthlyPlan().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal monthlyCompletionRate = vo.getOutsourceMonthlyActual()
                        .divide(vo.getOutsourceMonthlyPlan(), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
                vo.setOutsourceMonthlyCompletionRate(monthlyCompletionRate.setScale(2, RoundingMode.HALF_UP));
            }
            
            vo.setOutsourceMonthlyYoyRate(outsourceMonthlyData.getMonthlyYoyRate());
        }
        
        return vo;
    }

    @Override
    public List<CoalStrippingUnitsVO> getStrippingByUnits(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 查询各单位年度数据（year_month_type=0, unit_type IS NULL）
        LambdaQueryWrapper<CoalProdoperOsv> query = new LambdaQueryWrapper<>();
        query.eq(CoalProdoperOsv::getYear, year)
             .eq(CoalProdoperOsv::getYearMonthType, false)
             .isNull(CoalProdoperOsv::getUnitType)
             .ne(CoalProdoperOsv::getUnitCode, "TOTAL")
             .orderByAsc(CoalProdoperOsv::getUnitCode);
        
        List<CoalProdoperOsv> dataList = this.list(query);
        
        // 转换为VO列表
        List<CoalStrippingUnitsVO> resultList = new ArrayList<>();
        for (CoalProdoperOsv data : dataList) {
            CoalStrippingUnitsVO vo = new CoalStrippingUnitsVO();
            vo.setUnitName(data.getUnitName());
            vo.setUnitCode(data.getUnitCode());
            vo.setAnnualPlan(data.getAnnualPlan());
            vo.setAnnualActual(data.getAnnualActual());
            resultList.add(vo);
        }
        
        return resultList;
    }

    @Override
    public List<CoalStrippingTrendVO> getStrippingTrend(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        // 查询最近5年的年度数据（year_month_type=0, unit_code='TOTAL'）
        List<Integer> years = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            years.add(currentYear - i);
        }
        
        LambdaQueryWrapper<CoalProdoperOsv> query = new LambdaQueryWrapper<>();
        query.in(CoalProdoperOsv::getYear, years)
             .eq(CoalProdoperOsv::getYearMonthType, false)
             .eq(CoalProdoperOsv::getUnitCode, "TOTAL")
             .orderByDesc(CoalProdoperOsv::getYear);
        
        List<CoalProdoperOsv> dataList = this.list(query);
        
        // 转换为VO列表
        List<CoalStrippingTrendVO> resultList = new ArrayList<>();
        for (CoalProdoperOsv data : dataList) {
            CoalStrippingTrendVO vo = new CoalStrippingTrendVO();
            vo.setYear(data.getYear());
            vo.setAnnualPlan(data.getAnnualPlan());
            vo.setAnnualActual(data.getAnnualActual());
            vo.setAnnualCompletionRate(data.getAnnualCompletionRate());
            resultList.add(vo);
        }
        
        return resultList;
    }

}
